package jeye.dao;


import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import jeye.dao.model.Event;
import jeye.dao.model.EventFrame;

import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapExecutor;

public class EventDAO extends SqlMapClientDaoSupport {
	
	public long saveMotionDetectionEvent(final long timestamp, final int framerate) {
		final Event event = new Event();
		
		event.setFramerate(framerate);
		event.setTimestamp(timestamp);

		getSqlMapClientTemplate().insert("event.insertEvent", event);

		return event.getId();
	}
	
	public void saveMotionDetectionImages(final long eventId, final Map<Long, byte[]> framesMap) {
		getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
			public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
				executor.startBatch();
				
				for(Map.Entry<Long, byte[]> entry : framesMap.entrySet()) {
					EventFrame eventFrame = new EventFrame();
					
					eventFrame.setTimestamp(entry.getKey());
					eventFrame.setEventId(eventId);
					eventFrame.setFrame(entry.getValue());
					
					executor.insert("event.insertEventFrame", eventFrame);
				}
				
				executor.executeBatch();
				
				return null;
			}
		});
		
		
	}
	
	@SuppressWarnings("unchecked")
	public List<Long> getEventsIds() {
		return getSqlMapClientTemplate().queryForList("event.selectEventIds");
	}
	
	@SuppressWarnings("unchecked")
	public List<Long> getEventsFramesIds(Long eventId) {
		return getSqlMapClientTemplate().queryForList("event.selectEventFramesIds", eventId); 
	}
	
	public EventFrame getFrame(Long frameId) {
		return (EventFrame)getSqlMapClientTemplate().queryForObject("event.selectFrameById", frameId);
	}
	
	@SuppressWarnings("unchecked")
	public List<EventFrame> getEventFrames(Long eventId) {
		return getSqlMapClientTemplate().queryForList("event.selectEventFrames", eventId);
	}
	
}
